package com.lihang0328.groupmessageangel;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

public class MainActivity extends AppCompatActivity {
    private Button choose_btn;
    private Button choose_btn2;
    private Button choose_btn3;
    private Button choose_btn4;
    public String EXCEL_PATH="";
    private boolean canRead=false;
    private boolean canReadAdd=false;
    //工作方式选择code
    public final int EXCEL_SELECT_CODE=10001;
    public final int TXT_SELECT_CODE=10002;
    public final int LIST_SELECT_CODE=10003;
    //申请权限返回code
    private final int REQUEST_CODE_ASK_CALL_READEXCEL=10010;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        canReadFile();
        System.out.println("qwer:");
        String line = "lisi    1233";
        String[] str = line.split("\\s+");
        System.out.println(str.length + " " + str[0] + " " + str[1]);
        System.out.println("李行12,".length());
        System.out.println("qwer/wewf/asa.txt".matches("^.*\\.(xls|txt)$"));
        System.out.println("qwer/wewf/asa.xls".matches("^.*\\.(xls|txt)$"));
        System.out.println("qwer/wewf/asa.xlsx".matches("^.*\\.(xls|txt)$"));
        System.out.println("1234402".matches("[0-9]*"));
        System.out.println("1234x402".matches("[0-9]*"));
        View v= findViewById(R.id.ac_main);
        v.getBackground().setAlpha(210);
//        View myLayout = View.inflate(this, R.layout.activity_main, null);
        choose_btn = findViewById(R.id.btn_main_choose);
        choose_btn2 = findViewById(R.id.btn_main_choose2);
        choose_btn3 = findViewById(R.id.btn_main_choose3);
        choose_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(canRead){
                    showFileChooser(EXCEL_SELECT_CODE);
                }else {
                    Toast.makeText(MainActivity.this,"请给予内存访问权限以读取文件",Toast.LENGTH_SHORT).show();
                }
            }
        });
        choose_btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(canRead){
                    showFileChooser(TXT_SELECT_CODE);
                }else {
                    Toast.makeText(MainActivity.this,"请给予内存访问权限以读取文件",Toast.LENGTH_SHORT).show();
                }
            }
        });
        choose_btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(canReadAdd) {
                    Bundle bundle = new Bundle();
                    bundle.putString("PATH", "");
                    bundle.putString("ORIGIN", String.valueOf(LIST_SELECT_CODE));
                    Intent intent = new Intent(MainActivity.this, ContextActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else {
                    Toast.makeText(MainActivity.this,"请给予通讯录访问权限以读取联系人",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 展示文件管理器
     * @param num
     */
    private void showFileChooser(int num) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult( Intent.createChooser(intent, "选择一个文件管理器"), num);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "请安装一个文件管理器",  Toast.LENGTH_SHORT).show();
        }
    }
    ///storage/emulated/0/Documents/test.xls
    //content://cn.wps.moffice_eng.fileprovider/external/Documents/test.xls content /external/Documents/test.xls

    /**
     * 窗口返回读取相应文件
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)  {
        System.out.println("lihang:" + requestCode);
        switch (requestCode) {
            case EXCEL_SELECT_CODE:
            case TXT_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    // Get the Uri of the selected file
                    Uri uri = data.getData();
                    System.out.println("lihang:" + uri + " " + uri.getScheme() + " " + uri.getPath());
                    String uritmp = uri.toString().replaceAll("%3A", ":");
//                    uri = Uri.parse(uritmp);
                    EXCEL_PATH = FileUtils.getPath(this, uri);
                    System.out.println("lihang:"+ EXCEL_PATH);
                    if(EXCEL_PATH == null) EXCEL_PATH = "/storage/emulated/0"+uri.getPath().replace("/external", "").replace("/document/home:","/documents/");
                    System.out.println(EXCEL_PATH);
                    System.out.println(EXCEL_PATH.matches("^.*\\.(xls|txt)$"));
                    if(EXCEL_PATH.matches("^.*\\.(xls|txt)$")) {
                        Toast.makeText(MainActivity.this,"通讯录读取成功",Toast.LENGTH_SHORT).show();
                        Bundle bundle=new Bundle();
                        bundle.putString("PATH",EXCEL_PATH);
                        bundle.putString("ORIGIN","1");
                        Intent intent=new Intent(MainActivity.this,ContextActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }else if(EXCEL_PATH.matches("^.*?\\.(xlsx)$")){
                        Toast.makeText(MainActivity.this,"请使用.xls的Excel表格",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(MainActivity.this,"文件格式错误",Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case LIST_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = new Bundle();
                    bundle.putString("PATH", "");
                    bundle.putString("ORIGIN", "3");
                    Intent intent = new Intent(MainActivity.this, ContextActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 判断读取文件和通讯录权限是否开启
     */
    private void canReadFile() {
        int checkSendEmailPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS);
        int checkReadFilePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        int checkReadAddPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
        int all = 0;
        if(checkSendEmailPermission != PackageManager.PERMISSION_GRANTED) ++ all;
        if(checkReadFilePermission != PackageManager.PERMISSION_GRANTED) ++ all;
        if(checkReadAddPermission != PackageManager.PERMISSION_GRANTED) ++ all;
        String [] perm = new String[all];
        all = 0;
        if(checkSendEmailPermission != PackageManager.PERMISSION_GRANTED) {
            perm[all] = Manifest.permission.SEND_SMS;
            ++ all;
        }
        if(checkReadFilePermission != PackageManager.PERMISSION_GRANTED) {
            perm[all] = Manifest.permission.READ_EXTERNAL_STORAGE;
            ++ all;
        }else canRead = true;
        if(checkReadAddPermission != PackageManager.PERMISSION_GRANTED) {
            perm[all] = Manifest.permission.READ_CONTACTS;
            ++ all;
        }else canReadAdd = true;
        Log.e("File操作日志", "lihangquanxian num: " + all);
        if(all != 0) {
            //if ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS)
            ActivityCompat.requestPermissions(this, perm, REQUEST_CODE_ASK_CALL_READEXCEL);
        }
    }
    /**
     * 申请权限结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        System.out.println("requestCode:"+requestCode);
        switch (requestCode) {
            case REQUEST_CODE_ASK_CALL_READEXCEL:
                int len = grantResults.length;
                System.out.println("quanxian len: " + len);
                for(int i = 0; i < len; ++i) {
                    System.out.println(permissions[i] + " " + grantResults[i]);
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        if(permissions[i].equals(Manifest.permission.READ_EXTERNAL_STORAGE)) canRead = true;
                        else if(permissions[i].equals(Manifest.permission.READ_CONTACTS)) canReadAdd = true;
                    }
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}


